package com.unlcn.ils.kas.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.unlcn.ils.kas.dao.model.order.*;
import com.unlcn.ils.kas.service.order.*;
import com.unlcn.ils.kas.service.util.ErpUrl;
import com.unlcn.ils.kas.service.util.HttpClientUtil;
import com.unlcn.ils.kas.service.util.enums.order.CustomNoEnum;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 江铃控股订单调度 service 实现
 * @author 罗必量
 */
@Service
public class GetKgOrderServiceImpl implements GetKgOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetKgOrderServiceImpl.class);

    /**
     * 订单在途日志 service
     */
    @Autowired
    private HoldingOrderService holdingOrderService;

    /**
     * erp 接口地址 model
     */
    @Autowired
    private ErpUrl erpUrl;

    /**
     * 获取订单详情、订单在途信息 定时任务
     */
    @Override
    public Map<String, Object> getOrder(String startTime, String endTime) {
        LOGGER.info("手动拉取控股订单 params {} ", startTime, endTime);

        Map<String, Object> resultMap = new HashMap<>();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 获取订单号
        List<NameValuePair> orderParams = new ArrayList<>();
        orderParams.add(new BasicNameValuePair("icustomerid", CustomNoEnum.KG.getValue()));
        orderParams.add(new BasicNameValuePair("startTime", startTime));
        orderParams.add(new BasicNameValuePair("endTime", endTime));
        Date callStartTime = new Date();
        String getOrderNoResult = HttpClientUtil.get(erpUrl.getGetErpKgOrderNo(), orderParams, 600000000);
        Date callEndTime = new Date();
        if (StringUtils.isEmpty(getOrderNoResult)) {
            resultMap.put("结果", "请求订单号接口异常");
            return resultMap;
        }

        // 将订单号转换成map集合
        List<Map> orderMapNoList = holdingOrderService.getMap(getOrderNoResult);
        LOGGER.info(simpleDateFormat.format(new Date()) + "拉取了" + orderMapNoList.size() + "条订单(控股)");

        if (orderMapNoList.size() == 0) {
            resultMap.put("结果", "无可拉取订单");
            return resultMap;
        }

        // 遍历转换成的mao，一一存储进数据库
        Integer successNum = 0;
        List<Map<String, String>> errorList = new ArrayList<>();
        for (Map map : orderMapNoList) {
            String vcdn = map.get("vcdn").toString();

            try {
                // 请求获取订单详情
                List<NameValuePair> orderDetailParams = new ArrayList<>();
                orderDetailParams.add(new BasicNameValuePair("vcdn", vcdn));
                String getOrderDetailResult = HttpClientUtil.get(erpUrl.getGetErpOrderDetail(), orderDetailParams, 600000000);
                LOGGER.info("(" + vcdn + ")获取订单详情接口返回信息: ", getOrderDetailResult);
                if (StringUtils.isEmpty(getOrderDetailResult))
                    continue;

                // 格式化返回的订单详情信息
                JSONObject json = JSONObject.parseObject(getOrderDetailResult);
                Object obj = json.get("data");
                LOGGER.info("(" + vcdn + ")" + "详情: ", obj);
                if (obj == null)
                    continue;
                OrderOtdLog orderOtdLog = holdingOrderService.analysisOrder((Map)obj);
                orderOtdLog.setCallUrl(erpUrl.getGetErpKgOrderNo());
                orderOtdLog.setCallStartTime(callStartTime);
                orderOtdLog.setCallEndTime(callEndTime);

                List<NameValuePair> onWayParams = new ArrayList<>();
                onWayParams.add(new BasicNameValuePair("vcdn", orderOtdLog.getSysOrderNo()));
                String onWayResult = HttpClientUtil.get(erpUrl.getGetErpOnway(), onWayParams, 600000000);

                List<OrderOtdLogDetail> orderOtdLogDetailList = new ArrayList<>();
                if (!StringUtils.isEmpty(onWayResult)) {
                    // 将在途信息转换成map集合
                    List<Map> onWayList = holdingOrderService.getMap(onWayResult);

                    if (!CollectionUtils.isEmpty(onWayList)) {
                        for (Map onWayMap : onWayList) {
                            OrderOtdLogDetail orderOtdLogDetail = holdingOrderService.analysisOnWayInfo(onWayMap);
                            orderOtdLogDetailList.add(orderOtdLogDetail);
                        }
                    }
                }

                // 保存订单详细信息、在途信息
                holdingOrderService.saveOrderInfo(orderOtdLog, orderOtdLogDetailList);
                successNum ++;
            } catch (Exception e) {
                LOGGER.error("拉取订单" + vcdn + "发生异常", e);

                Map<String, String> errorMap = new HashMap<>();
                errorMap.put("订单号", vcdn);
                errorMap.put("异常信息", JSON.toJSONString(e));

                errorList.add(errorMap);

                continue;
            }
        }

        if (!CollectionUtils.isEmpty(errorList)) {
            resultMap.put("errorList", errorList);
        }

        resultMap.put("结果", "拉取了" + successNum + "条订单");

        return resultMap;
    }
}
